package cn.phecda.boot.common.lang.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.phecda.boot.common.lang.constants.DefaultConsts;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.lang.NonNull;

import java.util.List;

/**
 * <p> http 头工具 </p>
 *
 * @author : wanpinwei
 */
public final class HttpHeaderUtils {
    public static String getTenantId(ServerHttpRequest httpServletRequest) {
        return getTopHeader(httpServletRequest, DefaultConsts.HTTP_HEADER_TENANT_ID);
    }

    public static String getTenantId(HttpServletRequest httpServletRequest) {
        return getHeader(httpServletRequest, DefaultConsts.HTTP_HEADER_TENANT_ID);
    }

    @NonNull
    public static List<String> getHeaders(HttpHeaders httpHeaders, String name) {
        return CollectionUtil.emptyIfNull(httpHeaders.get(name));
    }

    @NonNull
    public static List<String> getHeaders(ServerHttpRequest serverHttpRequest, String name) {
        return CollectionUtil.emptyIfNull(getHeaders(serverHttpRequest.getHeaders(), name));
    }

    public static String getTopHeader(HttpHeaders httpHeaders, String name) {
        return top(getHeaders(httpHeaders, name));

    }

    public static String getTopHeader(ServerHttpRequest serverHttpRequest, String name) {
        return getTopHeader(serverHttpRequest.getHeaders(), name);
    }

    public static String getHeader(HttpServletRequest httpServletRequest, String name) {
        return httpServletRequest.getHeader(name);
    }

    public static boolean hasHeader(HttpHeaders httpHeaders, String name) {
        return httpHeaders.containsKey(name);
    }

    public static Boolean hasHeader(HttpServletRequest httpServletRequest, String name) {
        return StringUtils.isNoneBlank(getHeader(httpServletRequest, name));
    }

    public static Boolean hasHeader(ServerHttpRequest serverHttpRequest, String name) {
        return hasHeader(serverHttpRequest.getHeaders(), name);
    }

    private static String top(List<String> list) {
        if (list.isEmpty()) {
            return null;
        }

        return list.get(0);
    }

}
